import axios from "axios";
import { ElLoading, ElMessage, ElNotification } from 'element-plus';
import { h } from 'vue';
import store from '@/store/index.js'; // 导入 Vuex store

let loadingObj = null;

// 创建axios实例
const Service = axios.create({
    timeout: 5000,
    baseURL: "http://127.0.0.1:5362",
    headers: {
        "Content-Type": "application/json;charset=utf-8",
    }
});

// 请求拦截
Service.interceptors.request.use(async config => {
    // console.log('请求开始');
    // 获取 token 并添加到请求头中
    const token = store.state.uInfo.token || localStorage.getItem("token");
    if (token) {
        config.headers['Authorization'] = token;
    }


    loadingObj = ElLoading.service({
        lock: true,
        // fullscreen: true,
        text: '加载中...',
        background: 'rgba(0,0,0,0.3)',
        // background: 'rgba(255,255,255,0.3)',
        // customClass: 'loader',
        // spinner: 'false', // 使用自定义加载组件
    });
    return new Promise(resolve => {
        resolve(config);
    });
}, error => {
    if (loadingObj) loadingObj.close(); // 在出错时关闭loading
    return Promise.reject(error);
});

// 响应拦截
Service.interceptors.response.use(response => {
    // console.log('1213', response.data.message);
    const messageContent = response.data.wrongMessage;
    if (loadingObj) loadingObj.close();
    if (response.data.wrongMessage) {
        ElNotification({
            title: '提示',
            dangerouslyUseHTMLString: true,
            message: messageContent,
        });
    }
    return response.data;
}, err => {
    if (loadingObj) loadingObj.close();
    ElMessage({
        message: "服务器错误",
        type: "error",
        duration: 3000,
    });
    return Promise.reject(err);
});

// post请求
export const post = config => {
    return Service({
        ...config,
        method: "post",
        data: config.data,
    });
};

// get请求
export const get = config => {
    return Service({
        ...config,
        method: "get",
        // data: config.data,
    });
};
